﻿using mozhi.smarterp.AuthorCenter.Departments.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.AuthorCenter.Departments.Sevices
{
    public class DepartmentManager : DomainService
    {
        private IDepartmentRepository _repository;
        private IGuidGenerator _guidGenerator;

        public DepartmentManager(IDepartmentRepository repository , IGuidGenerator guidGenerator)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
        }

        public async Task<Department> GetAsync(Guid? id, string code, string name, Guid? parentId, bool activated)
        {
            var matchCount = await GetCountAsync(code, name, parentId, id);

            if (matchCount > 0)
                throw new UserFriendlyException($"编号或者名称已经存在：{code} {name}", "100000");

            Department department = null;

            if (id.HasValue)
            {
                department = await _repository.GetAsync(id.Value);

                if (department == null)
                    throw new UserFriendlyException($"部门：{id}不存在", "100000");

                department.Change(code, name, activated);
            }
            else
                department = new Department(_guidGenerator.Create(), code, name, activated);

            await SetParentDepartmentAsync(department, parentId);

            return department;
        }


        public async Task SetParentDepartmentAsync(Department department , Guid? parentId)
        {
            if (!parentId.HasValue)
                return;

            var parent = await _repository.GetAsync(parentId.Value);

            if (parent == null)
                throw new UserFriendlyException($"父级部门：{parentId}不存在", "100000");

            if (!parent.Activated)
                throw new UserFriendlyException($"父级部门：{parent.Name}已禁用", "100000");

            department.SetParentId(parentId);
        }

        #region
        private async Task<int> GetCountAsync(string code, string name, Guid? parentId, Guid? currentId)
        {
            var codeCount = await _repository.GetCountAsync(code, null, parentId, currentId);

            var nameCount = await _repository.GetCountAsync(null, name, parentId, currentId);

            return codeCount + nameCount;
        }
        #endregion
    }
}
